package com.kevin.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.kevin.configuration.model.Controller;

public class Configuration {	
	private static String configName = "knweb-config.xml";
	public static Controller controller = new Controller();
	static{
		init();
	}
	
	
	public static void configure(String configFilename){
		if(!configName.equals(configFilename)){
			configName = configFilename;
			init();
		}
	}
	
	@SuppressWarnings("unchecked")
	private static void init(){
		try {
			InputStream inputStream = Configuration.class.getClassLoader().getResourceAsStream(configName);
			InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
			Document document = new SAXBuilder().build(reader);
			Element rootElement = document.getRootElement();
			
			Element ctrlEle = rootElement.getChild("controller");
			List<Element> ctrlPropList = ctrlEle.getChildren();
			for(Element ctrlPro:ctrlPropList){
				String name = ctrlPro.getAttributeValue("name");
				if(name.equalsIgnoreCase("package")){
					System.out.println(ctrlPro.getAttributeValue("value"));
					controller.setPackageName(ctrlPro.getAttributeValue("value"));
				}
				
				if(name.equalsIgnoreCase("controller")){
					controller.setDefaultController(ctrlPro.getAttributeValue("value"));
				}
				
				if(name.equalsIgnoreCase("action")){
					controller.setDefaultAction(ctrlPro.getAttributeValue("value"));
				}
			}
			
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}

	}
}
